package com.yaorange.jk.web;

import com.yaorange.jk.entity.LoginLog;
import com.yaorange.jk.entity.User;
import com.yaorange.jk.service.LoginLogService;
import com.yaorange.jk.utils.SysConstant;

import java.util.Date;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
	
	private String username;
	private String password;
	private String errorMsg;
	@Autowired
	private LoginLogService loginLogService;
	public String login(){
		if(username!=null&&!username.isEmpty()&&password!=null&&!password.isEmpty())
		{
			try{
				//获取shiro中的subject(当前用户)
				Subject subject = SecurityUtils.getSubject();
				//将表单数据封装到token实体对象
				//token-->令牌
				UsernamePasswordToken token = new UsernamePasswordToken(username,password);
				subject.login(token);

				//将用户信息保存到session中
				User user = (User) subject.getPrincipal();

				ServletActionContext.getRequest().getSession().setAttribute(SysConstant.CURRENT_USER_INFO,user);
				
				LoginLog log=new LoginLog();
				log.setLoginName(user.getUserName());
				log.setLoginIp(ServletActionContext.getRequest().getRemoteAddr());
				log.setDate(new Date());
				loginLogService.save(log);
			}
			catch (Exception e)
			{
				errorMsg = "账号或者密码有错!";
				e.printStackTrace();
				return "login";
			}
		}else
		{
			return "login";
		}
		
		return "success";
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getErrorMsg() {
		return errorMsg;
	}
}
